<template>
    <div class="form-data-rules">
        <table class="table table-bordered m-table-border">
            <thead>
            <tr>
                <th style="width: 25%;">参数名</th>
                <th style="width:85px;">参数值来源</th>
                <th colspan="2">参数值</th>
            </tr>
            </thead>
            <tbody>
            <template v-for="(dr, idx) in dataRuleList">
            <tr :key="dr">
                <td>
                    <el-input v-model="dr.name" size="mini"></el-input>
                </td>
                <td>
                    <el-select v-model="dr.val_type" size="mini">
                        <el-option label="固定值" key="fixed" value="fixed"></el-option>
                        <el-option label="数据值" key="data" value="data"></el-option>
                        <!--<el-option label="登录人" key="admin" value="admin"></el-option>-->
                        <el-option label="页面入参" key="param" value="param"></el-option>
                    </el-select>
                </td>
                <td>
                    <template v-if="dr.val_type === 'fixed'">
                        <el-input v-model="dr.value" size="mini"></el-input>
                    </template>
                    <template v-else-if="dr.val_type === 'data'">
                        <el-select v-model="dr.dataValue" v-if="iForm"
                                   filterable placeholder="表单项" size="mini" >
                            <!-- admin 个性化 -->
                            <template v-if="isAdmin">
                                <el-option value="owner_id" label="登录ID"></el-option>
                            </template>
                            <template v-else>
                                <el-option value="_data_id" label="数据ID"></el-option>
                            </template>
                            <template v-for="it in iForm.items">
                                <!-- admin 个性化 -->
                                <!--<el-option v-if="isAdmin && it.name === 'id'" :key="it" value="owner_id" :label="it.label"></el-option>-->
                                <el-option v-if="checkItemSupportRule(it)"
                                           :value="it.name" :key="it.name" :label="it.label"></el-option>
                            </template>
                        </el-select>
                    </template>
                    <template v-else-if="dr.val_type === 'param'">
                        <el-input v-model="dr.paramValue" size="mini"></el-input>
                    </template>
                </td>
                <td style="width:30px;">
                    <i class="el-icon-error remove-btn" @click="handleRemoveDataRule(idx)"></i>
                </td>
            </tr>
            </template>
            </tbody>
        </table>
        <el-button type="primary" class="fixed-width" icon="el-icon-plus" size="mini" plain
                   :disabled="!iForm || !iForm.items || !iForm.items.length"
                   @click="handleAddDataRule()">添加参数</el-button>
    </div>
</template>

<script>
    import { mapState, mapActions } from 'vuex';
    import _ from 'lodash';

    /**
     链接组件跳转参数 link.query 设置
     固定值:    type: 1
     数据值：   type: $data.type
     人员值：   type: $admin.type (数据所属人员)
     本人值：   type: $my.type    (当前登录人员)
     入参值：   type: $param.type

     最终 link.query值举例:
     {
         startTime: 2021-01-01 00:00:00,
         type: $data.type,
         userName: $admin.username,
         hello: $param.helo
     }
     **/
    export default {
        name: 'LinkParam',
        model: {
            prop: 'value',
            event: 'change'
        },
        props: [ 'value', 'inputForm', 'inputFormId', 'inputFormViewId', 'inputFormCode', 'inputFormViewCode', 'isAdmin', 'hasParam' ],
        data() {
            return {
                loading: false,
                parsing: false,

                adminForm: null,
                iForm: null,
                rules: {},
                dataRuleList: []
            }
        },
        components: {

        },
        created: function () {

        },
        mounted: function () {
            this.parseRule2List();
            this.init();
        },
        watch: {
            'dataRuleList': {
                deep: true,
                handler: function() {
                    if(this.parsing) return;
                    this.ruleList2json();
                }
            },
            /*'initRules': {
                deep: true,
                handler: function(val) {
                    this.parseRule2List();
                }
            },*/
            'rules': {
                deep: true,
                handler: function(val) {
                    this.$emit('change', val)
                }
            },
            'inputForm': {
                deep: true,
                handler: function(val) {
                    // console.log('input form change ... ',val);
                    this.init();
                }
            },
            'inputFormId'() {
                this.init();
            },
            'inputFormCode'() {
                this.init();
            },
            'value': {
                deep: true,
                handler: function (newVal, oldVal) {
                    this.willReceiveProps(newVal, oldVal);
                }
            }
        },
        filters: {

        },
        computed: {
            ...mapState([
                'loginUser',
                'project'
            ])
        },
        methods: {
            ...mapActions([
            ]),
            // 避免双向绑定 可能导致的无限循环
            willReceiveProps(newVal, oldVal) {
                // console.log(newVal, oldVal);
                if(!this.$utils.deepEquals(newVal, this.rules)) {
                    this.rules = newVal;
                    this.parseRule2List();
                }
            },
            async init() {

                if(this.inputForm) {
                    this.iForm = this.inputForm;
                    // this.$set(this, 'iForm', this.inputForm)
                } else if(this.inputFormId) {
                    this.iForm = await this.$japi.form.getFormById(this.inputFormId, this.inputFormViewId);
                } else if(this.inputFormCode) {
                    this.iForm = await this.$japi.form.getFormByCode(this.inputFormCode, this.inputFormViewCode);
                }

                /*if(!this.adminForm) {
                    this.adminForm = await this.getAdminForm();
                }

                if(this.isAdmin && !this.iForm) {
                    this.iForm = this.adminForm;
                }*/
            },
            /*async getAdminForm() {

                let adminForm = await this.$japi.form.getFormByCode("_ADMIN");

                let items = _.get(adminForm, 'items', []);

                let fixedItems = [
                    { name: 'dept_id', label: '部门', type: 'dept' },
                    /!* { name: 'dept_post_id', label: '职务', type: 'deptpost' }, *!/
                    { name: 'loginname', label: '登录名', type: 'input' },
                    { name: 'mobile', label: '手机号', type: 'mobile' },
                    { name: 'nickname', label: '姓名', type: 'input' },
                    { name: 'id', label: '人员ID', type: 'user' },
                    /!*{ name: 'num', label: 'number测试', type: 'number' }*!/
                ];

                for(let i = 0; i < fixedItems.length; i++) {
                    let it = fixedItems[i];
                    let name = it.name;

                    let idx = _.findIndex(items, { name: name });

                    if(idx < 0) {
                        items.unshift(it)
                    }
                }

                return adminForm;
            },*/
            /*initDataRules() {
                this.parseRule2List();
            },*/
            checkItemSupportRule(it) {
                let type = _.get(it, 'type') || it;
                let name = _.get(it, 'name');

                return [ 'input', 'number', 'radio', 'checkbox',
                         'time', 'slider', 'slider2', 'user',
                         'dept', 'deptpost', 'mobile', 'formrel' ].indexOf(type) >= 0 && name !== '_ADMIN_ID';
            },
            /*checkOpByPropItemType(op, propItemType) {
                let supports = OP_TYPE_MAP[ op ];

                if(supports && _.indexOf(supports, propItemType) >= 0) {
                    return true;
                }

                return false;
            },*/
            parseRule2List() {
                this.parsing = true;
                let dataRuleList = [];

                for(let prop in this.value) {
                    let val = this.value[ prop ];
                    let dataValue = null;
                    let paramValue = null;
                    let adminValue = null;
                    // let item = null;
                    // let type = 'input';
                    // let op = 'eq';
                    let name = prop;
                    // let nameArr = name.split('.');
                    let valType = 'fixed';

                    // if(nameArr && nameArr.length >= 2) {
                    //     name = nameArr[0];
                    //     op = nameArr[1];
                    // }

                    if(_.isString(val)) {
                        if(_.startsWith(val, '$self')) {
                            valType = 'admin';
                        } else if(_.startsWith(val, '$data')) {
                            valType = 'data';
                        } else if(_.startsWith(val, '$param')) {
                            valType = 'param';
                        }
                    }


                    // 名称不能以 _ 开头，_开头的为人员属性
                    if(_.startsWith(name, '_')) name = name.substr(1);

                    /*item = _.find(_.get(this.inputForm, 'items'), { name: name });
                    type = _.get(item, 'type', 'input');

                    if(op === 'in') {
                        range = val;
                    } else if(op === 'between') {
                        if(type === 'number') {
                            min = _.get(val, '[0]');
                            max = _.get(val, '[1]');
                        } else {
                            range = val;
                        }
                    }*/

                    if(valType === 'admin') {
                        adminValue = val.replace(/^\$admin\./, '');
                        val = '';
                    } else if(valType === 'param') {
                        paramValue = val.replace(/^\$param\./, '');
                        val = '';
                    } else if(valType === 'data') {
                        dataValue = val.replace(/^\$data\./, '');
                        val = '';
                    }

                    dataRuleList.push(_.assign({
                        name: name,
                        val_type: valType,      // fixed / dync
                        value: val,
                        dataValue: dataValue,
                        paramValue: paramValue,
                        adminValue: adminValue,
                        // itemDef: item
                    }, ))
                }

                this.dataRuleList = dataRuleList;
                this.parsing = false;
            },
            handleAddDataRule() {
                let dataRuleList = this.dataRuleList;
                if(!dataRuleList) {
                    dataRuleList = [];
                }

                dataRuleList.push({
                    name: "",
                    value: "",
                    dataValue: null,
                    adminValue: null,
                    paramValue: null,
                    val_type: 'fixed',                  // fixed / dync / param
                });
                this.dataRuleList = dataRuleList;
            },
            handleRemoveDataRule(idx) {
                this.dataRuleList.splice(idx, 1);
            },
            /*handleDataRulePropChange(it) {
                if(!it) return;

                let type = 'input';
                let name = it.prop;
                let item = null;

                item = _.find(_.get(this.inputForm, 'items'), { name: name });
                type = _.get(item, 'type', 'input');


                it.prop_item_type = type;
                it.itemDef = item;

                if(it.prop && it.val_type === 'dync') {
                    let idx = _.findIndex(_.get(this.adminForm, 'items'), { name: it.prop });

                    if(it.prop === 'owner_id' || it.prop === 'dept_id') {
                        it.dyncValue = '$self';
                    } else if(idx >= 0) {
                        it.dyncValue = `$self.${ it.prop }`;
                    } else {
                        it.dyncValue = '';
                    }
                } else {
                    it.value = '';
                    it.paramValue = '';
                }
            },*/
            ruleList2json() {
                let mrule = {};
                for(let it of this.dataRuleList) {
                    let value = it.value;
                    let name = it.name;

                    if(!name) continue;

                    if(it.val_type === 'data') {
                        if(it.dataValue) {
                            if(_.startsWith(it.dataValue, '$data')) {
                                value = it.dataValue;
                            } else {
                                value = `$data.${it.dataValue}`;
                            }
                        }
                    } else if(it.val_type === 'param') {
                        if(it.paramValue) {
                            if(_.startsWith(it.paramValue, '$param')) {
                                value = it.paramValue;
                            } else {
                                value = `$param.${it.paramValue}`;
                            }
                        }
                    } else if(it.val_type === 'admin') {
                        if(it.adminValue) {
                            if(_.startsWith(it.adminValue, '$admin')) {
                                value = it.adminValue;
                            } else {
                                value = `$admin.${it.adminValue}`;
                            }
                        }
                    }

                    mrule[ name ] = value;
                }

                this.rules = mrule;
            }
        }
    }
</script>
<style scoped lang="scss">

</style>
